package com.kh.statistics.video.core.algorithm;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class SignatureGenerator {
    private static final String HMAC_SHA256 = "HmacSHA256";

    /**
     * 生成签名
     *
     * @param params 参数map
     * @param apiKey API密钥
     * @return 生成的签名（十六进制字符串）
     */
    public static String generateSignature(SortedMap<String, String> params, String apiKey) throws Exception {
        // 将参数拼接成字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (stringBuilder.length() > 0) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);  // 删除最后一个"&"
        }

        // 使用HMAC-SHA256算法生成签名
        Mac mac = Mac.getInstance(HMAC_SHA256);
        SecretKeySpec secretKeySpec = new SecretKeySpec(apiKey.getBytes(), HMAC_SHA256);
        mac.init(secretKeySpec);

        byte[] hash = mac.doFinal(stringBuilder.toString().getBytes());

        // 转换成十六进制字符串
        return bytesToHex(hash);
    }

    // 辅助方法，将字节转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        try {
            SortedMap<String, String> params = new TreeMap<>();
            params.put("count", "10");
            params.put("page", "3");
            params.put("kuaishou.web.cp.api_ph", "7f300e2b5b859e0cb14057bf2f109bf951b9");

            String apiKey = "7f300e2b5b859e0cb14057bf2f109bf951b9";
            String signature = generateSignature(params, apiKey);
            System.out.println("Generated Signature: " + signature);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}